package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description：保障项服务实现类
 */

public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    private  LambdaQueryWrapper<Safeguard> lpw(SafeguardVO safeguardVO){
        LambdaQueryWrapper<Safeguard> lambdaQueryWrapper = Wrappers.<Safeguard>lambdaQuery()
                .eq(StrUtil.isNotEmpty(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotEmpty(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotEmpty(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());
        return lambdaQueryWrapper;
    }

    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //TODO

        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), lpw(safeguardVO));
        Page<SafeguardVO> pageVo = BeanConv.toPage(page, SafeguardVO.class);
        return pageVo;
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO

        Safeguard safeguard = this.getById(safeguardId);
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }

    @Override
    @Transactional
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //TODO

        //判断key是否存在
        Integer count = lambdaQuery().eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count > 0) {
            log.error("key已存在");
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        //转化对象
        Safeguard bean = BeanConv.toBean(safeguardVO, Safeguard.class);
        this.save(bean);
        return BeanConv.toBean(bean, SafeguardVO.class);
    }

    @Autowired
    private IPlanSafeguardService planSafeguardService;
    @Autowired
    private ICategorySafeguardService categorySafeguardService;
    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        //TODO

        //判断key是否存在
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())//去掉自身
                .count();
        if (count > 0) {
            log.error("key已存在,{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //判断是否有别的关联关系
        Integer count1 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        Integer count2 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count1 > 0 || count2 > 0){
            log.error("存在关联关系,{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //执行修改
        boolean b = updateById(BeanConv.toBean(safeguardVO, Safeguard.class));
        if (!b){
            log.error("执行修改失败,{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        return b;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO

        List<String> ids = Arrays.asList(checkedIds);
        List<Safeguard> olds = listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream().map(Safeguard::getSafeguardKey).collect(Collectors.toSet());
        Integer count1 = planSafeguardService.lambdaQuery()
                .in(PlanSafeguard::getSafeguardKey, keySet)
                .eq(PlanSafeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        Integer count2 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getSafeguardKey, keySet)
                .eq(CategorySafeguard::getDataState,SuperConstant.DATA_STATE_0)
                .count();
        if(count1>0||count2>0){
            log.error("已被方案或分类关联，无法删除：{}",keySet);
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }

        return removeByIds(ids);
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        //TODO

        List<Safeguard> list = this.list(lpw(safeguardVO));
        return BeanConv.toBeanList(list, SafeguardVO.class);
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO

        return safeguardKeyList.stream().map(x -> findBySafeguardKey(x)).collect(Collectors.toList());
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO

        Safeguard safeguard = this.lambdaQuery().eq(Safeguard::getSafeguardKey, safeguardKey).one();
        if (safeguard == null){
            log.error("不存在,{}", safeguardKey);
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }
}
}
